package com.ai.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;

/**
 * @author daizy
 * 
 * 1.java中远程执行脚本工具类
 * 
 * 2015/06/16 09:40:00
 *
 */
public class ShellUtils {
	
	private final static Log logger = LogFactory.getLog(ShellUtils.class);
	
	
	private String ipAddress; 
	   
    private String username; 
   
    private String password; 
   
    public int port; 
   
    private List<String> stdout; 
   
    public ShellUtils(final String ipAddress, final String username, final String password,final int port) { 
        this.ipAddress = ipAddress; 
        this.username = username; 
        this.password = password; 
        this.port = port;
        stdout = new ArrayList<String>(); 
    }  
    
    public int execute(final String command) { 
        int returnCode = 0; 
        JSch jsch = new JSch(); 
        try { 
			jsch.getSession(username, ipAddress, port);
			com.jcraft.jsch.Session session = jsch.getSession(username, ipAddress, port);
			session.setPassword(password);
			//ssh自动把计算机的密匙加入"$HOME/.ssh/known_hosts"文件
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			session.setConfig(sshConfig);
            session.connect(); 
            Channel channel = session.openChannel("exec"); 
            ((ChannelExec) channel).setCommand(command); 
   
            channel.setInputStream(null); 
            BufferedReader input = new BufferedReader(new InputStreamReader(channel 
                    .getInputStream())); 
   
            channel.connect(); 
            System.out.println("The remote command is: " + command); 
            String line; 
            while ((line = input.readLine()) != null) { 
                stdout.add(line); 
            } 
            input.close(); 
            if (channel.isClosed()) { 
                returnCode = channel.getExitStatus(); 
            } 
            channel.disconnect(); 
            session.disconnect(); 
        } catch (Exception e) { 
        	logger.error("服务器执行脚本异常："+e.getMessage());
        } 
        return returnCode; 
    } 
   
    public List<String> getStandardOutput() { 
        return stdout; 
    } 
   
    public static void main(final String [] args) { 
    	ShellUtils sshExecutor = new ShellUtils("61.183.90.246", "dev_dh", "URXsp3lf",57286); 
        sshExecutor.execute("root@172.4.21.121 ;cd /home/;ls"); 
        List<String> stdout = sshExecutor.getStandardOutput(); 
        for (String str : stdout) { 
            System.out.println(str); 
        } 
    }  
	
}
